package com.innovation.ic.im.end.base.service.im_erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.RedisManager;
import com.innovation.ic.im.end.base.mapper.im_erp9.AccountMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.RefUserGroupAccountMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.UserGroupMapper;
import com.innovation.ic.im.end.base.model.im_erp9.Account;
import com.innovation.ic.im.end.base.model.im_erp9.RefUserGroupAccount;
import com.innovation.ic.im.end.base.model.im_erp9.UserGroup;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.innovation.ic.im.end.base.pojo.constant.ToppingType;
import com.innovation.ic.im.end.base.pojo.im_erp9.GroupPojo;
import com.innovation.ic.im.end.base.service.im_erp9.RefUserGroupAccountService;
import com.innovation.ic.im.end.base.vo.im_erp9.UserGroupAddMemberVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * RefUserGroupAccount的具体实现类
 */
@Service
@Transactional
public class RefUserGroupAccountServiceImpl extends ServiceImpl<RefUserGroupAccountMapper, RefUserGroupAccount> implements RefUserGroupAccountService {
    private static final Logger log = LoggerFactory.getLogger(RefUserGroupAccountServiceImpl.class);

    @Resource
    private RefUserGroupAccountMapper refUserGroupAccountMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private UserGroupMapper userGroupMapper;

    @Resource
    private RedisManager redisManager;

    /**
     * 根据userGroupId，查找username不在usernameList范围内的用户
     *
     * @param userGroupId
     * @param usernameList
     * @return
     */
    @Override
    public ServiceResult<List<RefUserGroupAccount>> findByUserGroupIdAndNotInList(Integer userGroupId, List<String> usernameList) {
        ServiceResult<List<RefUserGroupAccount>> serviceResult = new ServiceResult<List<RefUserGroupAccount>>();

        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_group_id", userGroupId);
        if (null != usernameList && usernameList.size() > 0) {
            queryWrapper.notIn("username", usernameList);
        }
        List<RefUserGroupAccount> refUserGroupAccountList = baseMapper.selectList(queryWrapper);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(refUserGroupAccountList);
        return serviceResult;
    }

    /**
     * 保存RefUserGroupAccount对象
     *
     * @param refUserGroupAccount
     * @return
     */
    @Override
    public ServiceResult<Boolean> saveRefUserGroupAccount(RefUserGroupAccount refUserGroupAccount) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        log.info("根据userGroupId=[{}],accountId=[{}],username=[{}]查询数据库记录",
                refUserGroupAccount.getUserGroupId(), refUserGroupAccount.getAccountId(), refUserGroupAccount.getUsername());
        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, refUserGroupAccount.getUserGroupId());
        queryWrapper.eq(Constants.ACCOUNT_ID_FIELD, refUserGroupAccount.getAccountId());
        queryWrapper.eq(Constants.USER_NAME, refUserGroupAccount.getUsername());
        Integer result = refUserGroupAccountMapper.selectCount(queryWrapper);
        if (result != null && result > 0) {
            log.info("数据库中已有userGroupId=[{}],accountId=[{}],username=[{}]的记录,不进行插入操作",
                    refUserGroupAccount.getUserGroupId(), refUserGroupAccount.getAccountId(), refUserGroupAccount.getUsername());
        } else {
            log.info("插入新数据");
            int insert = baseMapper.insert(refUserGroupAccount);
            log.info("insert data count : [{}]", insert);
        }

        // 更新自定义群成员数量
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, refUserGroupAccount.getUserGroupId());
        Integer count = refUserGroupAccountMapper.selectCount(queryWrapper);
        UserGroup userGroup = new UserGroup();
        userGroup.setMembership(count);
        UpdateWrapper<UserGroup> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(Constants.ID, refUserGroupAccount.getUserGroupId());
        int update = userGroupMapper.update(userGroup, updateWrapper);
        if (update > 0) {
            log.info("更新自定义群组:[{}]成员数量成功", refUserGroupAccount.getUserGroupId());
        }

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 添加自定义群组成员
     *
     * @param userGroupAddMemberVo 用户自定义群组添加成员vo类
     * @return 返回添加结果
     */
    @Override
    public ServiceResult<Boolean> addRefUserGroupMember(UserGroupAddMemberVo userGroupAddMemberVo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = Boolean.FALSE;
        String message = ServiceResult.INSERT_FAIL;
        List<RefUserGroupAccount> insertList = new ArrayList<>();

        // 检查list中需要插入数据库的id
        List<String> list = userGroupAddMemberVo.getNewMemberAccountIdList();
        for (String accountId : list) {
            if (accountId == null) {
                log.info("accountId值为null,无法进行插入操作,跳过当前数据进行处理");
                continue;
            }

            QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroupAddMemberVo.getUserGroupId());
            queryWrapper.eq(Constants.ACCOUNT_ID_FIELD, accountId);
            Integer selectCount = refUserGroupAccountMapper.selectCount(queryWrapper);
            if (selectCount > 0) {
                log.info("用户:[{}]在自定义群组:[{}]中已存在,无需插入", accountId, userGroupAddMemberVo.getUserGroupId());
                continue;
            }

            RefUserGroupAccount refUserGroupAccount = new RefUserGroupAccount();
            refUserGroupAccount.setUserGroupId(userGroupAddMemberVo.getUserGroupId());
            refUserGroupAccount.setAccountId(accountId);
            refUserGroupAccount.setUsername(getUserNameByAccountId(accountId));
            refUserGroupAccount.setNoReminder(0);
            refUserGroupAccount.setJoinGroupTime(new Date(System.currentTimeMillis()));
            insertList.add(refUserGroupAccount);
        }

        // 插入数据
        if (insertList != null && insertList.size() > 0) {
            Integer count = refUserGroupAccountMapper.insertBatchSomeColumn(insertList);
            if (count > 0) {
                result = Boolean.TRUE;
                message = ServiceResult.INSERT_SUCCESS;
            }
        } else {
            result = Boolean.TRUE;
            message = "当前用户组在群组中均已存在,无需重复插入";
            log.info(message);
        }

        serviceResult.setMessage(message);
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 设置某个用户对某个自定义群组是否消息免打扰
     *
     * @param userGroupId 自定义群组id
     * @param accountId   账号id
     * @param username    用户名
     * @param status      状态
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> noReminder(Integer userGroupId, String accountId, String username, Integer status) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        Boolean result = Boolean.FALSE;

        // 更新用户消息免打扰设置
        int i = refUserGroupAccountMapper.updateNoReminder(userGroupId, accountId, username, status);
        if (i > 0) {
            result = Boolean.TRUE;
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 将某个用户对某个自定义群组设置为置顶
     *
     * @param userGroupId
     * @param accountId
     * @param username
     * @return
     */
    @Override
    public ServiceResult<Boolean> topping(Integer userGroupId, String accountId, String username, Integer status) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<Boolean>();

        Boolean result = Boolean.FALSE;

        UpdateWrapper<RefUserGroupAccount> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_group_id", userGroupId);
        updateWrapper.eq("account_id", accountId);
        updateWrapper.eq("username", username);
        RefUserGroupAccount refUserGroupAccount = new RefUserGroupAccount();
        if (status.equals(ToppingType.YES)) {
            refUserGroupAccount.setToppingTime(new Date());
        } else {
            refUserGroupAccount.setToppingTime(null);
        }
        int update = refUserGroupAccountMapper.update(refUserGroupAccount, updateWrapper);
        if (update > 0) {
            result = Boolean.TRUE;
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 退出群聊。删除某个用户和某个自定义群组的关系，删除这个用户在这个自定义群组的未读消息
     *
     * @param userGroupId
     * @param accountId
     * @param username
     * @return
     */
    @Override
    public ServiceResult<Boolean> exit(Integer userGroupId, String accountId, String username) {
        Boolean result = Boolean.FALSE;

        //获取当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newLastLoginTime = sdf.format(date);
        //先把ref_user_group_account表数据存入his_ref_user_group_account历史表中
        refUserGroupAccountMapper.copyBy(newLastLoginTime, userGroupId, accountId, username);
        // 删除ref_user_group_account表中的记录
        QueryWrapper<RefUserGroupAccount> refUserGroupAccountQueryWrapper = new QueryWrapper<>();
        refUserGroupAccountQueryWrapper.eq("user_group_id", userGroupId);
        refUserGroupAccountQueryWrapper.eq("account_id", accountId);
        refUserGroupAccountQueryWrapper.eq("username", username);
        int delete = baseMapper.delete(refUserGroupAccountQueryWrapper);
        if (delete > 0) {
            result = Boolean.TRUE;
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 根据userGroupId，修改对应记录的last_contact_time字段
     *
     * @param userGroupId
     * @return
     */
    @Override
    public ServiceResult<Boolean> updateLastContactTimeByUserGroupId(Integer userGroupId) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 根据用户自定义群组id更新最近联系时间
        refUserGroupAccountMapper.updateLastContactTimeByUserGroupId(userGroupId);

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 根据条件查询自定义群组信息
     *
     * @param map 查询条件
     * @return 返回自定义群组信息
     */
    @Override
    public ServiceResult<GroupPojo> getGroupDetailInfoByParam(Map<String, Object> map) {
        ServiceResult<GroupPojo> serviceResult = new ServiceResult<GroupPojo>();

        log.info("根据查询条件:[{}]查询自定义群组信息", new JSONObject(map).toJSONString());
        GroupPojo groupPojo = refUserGroupAccountMapper.getGroupDetailInfoByParam(map);
        if (groupPojo != null) {
            // 根据查询条件查询账号信息集合
            log.info("根据查询条件:[{}]查询账号信息集合", new JSONObject(map).toJSONString());
            List<Account> accounts = accountMapper.selectAccountByUserGroupParam(map);
            if (accounts != null && accounts.size() > 0) {
                groupPojo.setAccountList(accounts);
            } else {
                log.info("查询自定义群组成员列表为空");
                groupPojo.setAccountList(new ArrayList<>());
            }
        } else {
            log.info("查询自定义群组信息为空,不进行自定义群组成员列表查询操作");
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(groupPojo);
        return serviceResult;
    }

    /**
     * 根据用户设置自定义群组聊天内容不可见时间
     *
     * @param map 更新条件
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> invisibleChatRecordSet(Map<String, Object> map) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        Boolean result = false;
        log.info("根据用户设置自定义群组聊天内容不可见时间,更新条件:[{}]", new JSONObject(map).toJSONString());

        // 更新用户对自定义群组的内容不可见时间
        int update = refUserGroupAccountMapper.updateContentInvisibleTime((String) map.get(Constants.USER_GROUP_ID), (String) map.get(Constants.ACCOUNT_ID), (String) map.get(Constants.USER_NAME));
        if (update > 0) {
            log.info("根据参数:[{}]设置自定义群组聊天记录不可见时间成功", new JSONObject(map).toJSONString());
            result = true;
        } else {
            log.warn("根据参数:[{}]设置自定义群组聊天记录不可见时间失败", new JSONObject(map).toJSONString());
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 删除最近联系自定义群组并清除聊天记录
     *
     * @param map 删除条件
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> deleteUserGroupChat(Map<String, Object> map) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = false;
        log.info("删除最近联系自定义群组并清除聊天记录,删除条件:[{}]", new JSONObject(map).toJSONString());

        // 删除最近联系自定义群组并清除聊天记录
        int update = refUserGroupAccountMapper.deleteUserGroupChat(map);
        if (update > 0) {
            log.info("根据参数:[{}]删除最近联系自定义群组并清除聊天记录成功", new JSONObject(map).toJSONString());
            result = true;
        } else {
            log.warn("根据参数:[{}]删除最近联系自定义群组并清除聊天记录失败", new JSONObject(map).toJSONString());
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 添加数据到redis
     *
     * @param userGroupId 为null全量添加,userGroupId不为null更新当前自定义群组信息
     * @return
     */
    @Override
    public ServiceResult<Boolean> importRefUserGroupAccountIntoRedis(Integer userGroupId) {
        ServiceResult<Boolean> returnResult = new ServiceResult<>();
        //userGroupId 为null全量添加,userGroupId不为null更新当前自定义群组信息
        if (userGroupId == null) {
            //全量添加用户自定义群组关系详情和群组的人数到redis
            addRefUserGroupAccountDetailAndCount();
        } else {
            addRefUserGroupAccountDetailAndCountByUserGroupId(userGroupId);
        }

        returnResult.setMessage(ServiceResult.SYNC_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }

    /**
     * 全量添加用户自定义群组关系详情和自定义群组人数到redis
     */
    public void addRefUserGroupAccountDetailAndCount() {
        log.info("全量添加用户自定义群组关系详情和自定义群组人数到redis,开始");
        //添加用户自定义群组详情
        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<RefUserGroupAccount>();
        List<RefUserGroupAccount> refUserGroupAccountList = refUserGroupAccountMapper.selectList(queryWrapper);
        for (RefUserGroupAccount refUserGroupAccount : refUserGroupAccountList) {
            GroupPojo groupPojo = new GroupPojo();
            BeanUtils.copyProperties(refUserGroupAccount, groupPojo);
            groupPojo.setId(refUserGroupAccount.getId().toString());
            groupPojo.setGroupId(refUserGroupAccount.getUserGroupId().toString());
            groupPojo.setName(userGroupMapper.selectById(refUserGroupAccount.getUserGroupId()).getName());
            groupPojo.setType(3);
            Map<String, Object> map = new HashMap<>();
            map.put(Constants.USER_GROUP_ID, refUserGroupAccount.getUserGroupId());
            List<Account> accounts = accountMapper.selectAccountByUserGroupParam(map);
            if (accounts != null && accounts.size() > 0) {
                groupPojo.setAccountList(accounts);
            } else {
                log.info("查询自定义群组成员列表为空");
                groupPojo.setAccountList(new ArrayList<>());
            }
            redisManager.set(RedisStorage.REF_USER_GROUP_ACCOUNT_DETAIL_PREFIX + refUserGroupAccount.getUserGroupId() +
                    RedisStorage.UNDERLINE + refUserGroupAccount.getAccountId() +
                    RedisStorage.UNDERLINE + refUserGroupAccount.getUsername(), JSON.toJSONString(groupPojo));
        }
        //添加自定义群组人数
        QueryWrapper<UserGroup> userGroupQueryWrapper = new QueryWrapper<UserGroup>();
        List<UserGroup> groupList = userGroupMapper.selectList(userGroupQueryWrapper);
        for (UserGroup userGroup : groupList) {
            QueryWrapper<RefUserGroupAccount> refUserGroupAccountQueryWrapper = new QueryWrapper<>();
            refUserGroupAccountQueryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroup.getId());
            Integer count = refUserGroupAccountMapper.selectCount(refUserGroupAccountQueryWrapper);
            redisManager.set(RedisStorage.REF_USER_GROUP_ACCOUNT_BY_GROUP_ID_COUNT_PREFIX + userGroup.getId(), JSON.toJSONString(count));
        }
        log.info("全量添加用户自定义群组关系详情和自定义群组人数到redis,结束");
    }

    /**
     * 根据userGroupId,添加用户自定义群组关系详情和自定义群组人数到redis
     */
    public void addRefUserGroupAccountDetailAndCountByUserGroupId(Integer userGroupId) {
        log.info("根据userGroupId,添加用户自定义群组关系详情和自定义群组人数到redis,开始,userGroupId:{}", userGroupId);
        //添加用户自定义群组详情
        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<RefUserGroupAccount>();
        queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroupId);
        List<RefUserGroupAccount> refUserGroupAccountList = refUserGroupAccountMapper.selectList(queryWrapper);
        for (RefUserGroupAccount refUserGroupAccount : refUserGroupAccountList) {
            GroupPojo groupPojo = new GroupPojo();
            BeanUtils.copyProperties(refUserGroupAccount, groupPojo);
            groupPojo.setId(refUserGroupAccount.getId().toString());
            groupPojo.setGroupId(refUserGroupAccount.getUserGroupId().toString());
            groupPojo.setName(userGroupMapper.selectById(refUserGroupAccount.getUserGroupId()).getName());
            groupPojo.setType(3);
            Map<String, Object> map = new HashMap<>();
            map.put(Constants.USER_GROUP_ID, refUserGroupAccount.getUserGroupId());
            List<Account> accounts = accountMapper.selectAccountByUserGroupParam(map);
            if (accounts != null && accounts.size() > 0) {
                groupPojo.setAccountList(accounts);
            } else {
                log.info("查询自定义群组成员列表为空");
                groupPojo.setAccountList(new ArrayList<>());
            }
            redisManager.set(RedisStorage.REF_USER_GROUP_ACCOUNT_DETAIL_PREFIX + refUserGroupAccount.getUserGroupId() +
                    RedisStorage.UNDERLINE + refUserGroupAccount.getAccountId() +
                    RedisStorage.UNDERLINE + refUserGroupAccount.getUsername(), JSON.toJSONString(groupPojo));
        }
        //添加自定义群组人数
        QueryWrapper<RefUserGroupAccount> refUserGroupAccountQueryWrapper = new QueryWrapper<>();
        refUserGroupAccountQueryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroupId);
        Integer count = refUserGroupAccountMapper.selectCount(refUserGroupAccountQueryWrapper);
        redisManager.set(RedisStorage.REF_USER_GROUP_ACCOUNT_BY_GROUP_ID_COUNT_PREFIX + userGroupId, JSON.toJSONString(count));
        log.info("根据userGroupId,添加用户自定义群组关系详情和自定义群组人数到redis,结束,userGroupId:{}", userGroupId);
    }

    /**
     * 通过id去ref_user_group_account表获取对应的 id
     *
     * @param id
     * @return
     */
    @Override
    public ServiceResult<List<RefUserGroupAccount>> findByRealId(String id) {
        ServiceResult<List<RefUserGroupAccount>> serviceResult = new ServiceResult<List<RefUserGroupAccount>>();
        List<RefUserGroupAccount> refUserGroupAccountList = refUserGroupAccountMapper.findByRealId(id);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(refUserGroupAccountList);
        return serviceResult;
    }

    /**
     * 根据自定义群组id获取群组人数
     *
     * @param userGroupId 自定义群组id
     * @return 群组人数
     */
    @Override
    public ServiceResult<Integer> getCountByUserGroupId(String userGroupId) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();

        // 查询自定义群组人数
        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroupId);
        Integer count = refUserGroupAccountMapper.selectCount(queryWrapper);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(count);
        return serviceResult;
    }

    /**
     * 查询当前自定义群组中除自己之外的用户账号
     *
     * @param userGroupId 自定义群组id
     * @param userName    用户名
     * @return 返回除自己之外的用户账号
     */
    @Override
    public ServiceResult<List<String>> getUserGroupAccountsNotHaveSelf(Integer userGroupId, String userName) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();

        // 查询当前自定义群组中除自己之外的用户账号
        List<String> result = refUserGroupAccountMapper.getUserGroupAccountsNotHaveSelf(userGroupId, userName);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 查询自定义群组中的用户账号
     *
     * @param userGroupId 自定义群组id
     * @return 返回自定义群组中的用户账号
     */
    @Override
    public ServiceResult<List<String>> getUserGroupAccounts(Integer userGroupId) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();

        // 查询当前自定义群组中除自己之外的用户账号
        List<String> result = refUserGroupAccountMapper.getUserGroupAccounts(userGroupId);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据自定义群组id获取自定义群组信息
     *
     * @param userGroupId 自定义群组id
     * @return 返回自定义群组信息
     */
    @Override
    public ServiceResult getUserGroupInfo(Integer userGroupId) {
        ServiceResult<JSONObject> serviceResult = new ServiceResult<>();
        JSONObject json = null;
        // 获取自定义群组信息
        UserGroup userGroup = userGroupMapper.selectById(userGroupId);
        if (userGroup != null) {
            json = new JSONObject();
            json.put(Constants.USER_GROUP, JSONObject.toJSON(userGroup));
            // 获取自定义群组成员信息
            QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroupId);
            List<RefUserGroupAccount> refUserGroupAccounts = refUserGroupAccountMapper.selectList(queryWrapper);
            if (refUserGroupAccounts != null && refUserGroupAccounts.size() > 0) {
                json.put(Constants.REF_USER_GROUP_ACCOUNTS, JSONObject.toJSON(refUserGroupAccounts));
            }
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(json);
        return serviceResult;
    }

    /**
     * 更新用户username自定义群组userGroupId的最近联系时间
     *
     * @param userGroupId 自定义群组id
     * @param accountId   用户账号
     * @param username    用户名
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> updateLastContactTime(String userGroupId, String accountId, String username) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = Boolean.FALSE;

        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, userGroupId);
        queryWrapper.eq(Constants.ACCOUNT_ID_FIELD, accountId);
        queryWrapper.eq(Constants.USER_NAME, username);
        List<RefUserGroupAccount> refUserGroupAccounts = refUserGroupAccountMapper.selectList(queryWrapper);
        if (refUserGroupAccounts.get(0).getLastContactTime() == null) {
            // 更新用户username自定义群组userGroupId的最近联系时间
            int update = refUserGroupAccountMapper.updateLastContactTime(userGroupId, accountId, username);
            if (update > 0) {
                result = true;
                log.info("更新用户:[{}]自定义群组:[{}]的最近联系时间成功", username, userGroupId);
            }
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据账号查询用户名
     *
     * @param accountId 账号
     * @return 返回用户名
     */
    private String getUserNameByAccountId(String accountId) {
        Account account = accountMapper.selectById(accountId);
        if (account != null && !Strings.isNullOrEmpty(account.getUsername())) {
            return account.getUsername();
        }
        return null;
    }
}